package main

import (
	"net"
	"fmt"
	"net/http"
	"encoding/json"
	"strings"
	"io/ioutil"
	"bufio"
)

func main() {
	tcpAddr, err := net.ResolveTCPAddr("", ":8293")
	if err != nil {
		fmt.Println("服务启动失败", err)
		return
	}

	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		fmt.Println("服务启动失败", err)
		return
	}

	fmt.Println("服务已启动")
	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		go handler(conn)
	}
}

type ResultInf struct {
	result_msg  string
	result_code string
}

func handler(conn net.Conn) {
	defer conn.Close()
	bufferReader := bufio.NewReader(conn)
	buf, _, err := bufferReader.ReadLine()
	if err != nil {
		result, _ := json.Marshal(ResultInf{"TCP服务【读取数据失败】", "000001"})
		conn.Write([]byte(result))
		conn.Write([]byte("\n"))
	}

	fmt.Println("客户端请求：", string(buf))
	dm := make(map[string]interface{})
	json.Unmarshal(buf, &dm)

	data, err := json.Marshal(dm["data"])
	if err != nil {
		result, _ := json.Marshal(ResultInf{"TCP服务【解析json数据错误】", "000001"})
		conn.Write([]byte(result))
		conn.Write([]byte("\n"))
		return
	}

	url := dm["url"]
	if url == nil {
		result, _ := json.Marshal(ResultInf{"TCP服务【请求报文格式错误】", "000001"})
		conn.Write([]byte(result))
		conn.Write([]byte("\n"))
		return
	}
	result := sendHttp(url.(string), string(data))
	conn.Write(result)
	conn.Write([]byte("\n"))
}

func sendHttp(url, data string) []byte {
	resp, err := http.Post(url, "application/json; encoding=utf-8", strings.NewReader(data))
	if err != nil {
		return []byte("TCP服务【请求网络失败】")
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	return body
}
